# -*- coding: utf-8 -*-

#from xml.dom import minidom
#from xml.etree import ElementTree
#import xml.etree.ElementTree as ET
#RESPONSE_FORMAT = 'xml'

import urllib


" my keys list "
#req_keys_list = {
#    'alisoft':['app_instance_id', 'token', 'user_id', 'app_id', 'target'],
#    'login': ['isp_username'],
#    }

validate_user_keys = 'sip_apiname', 'sip_appkey', 'sip_timestamp', 'userId', 'appInstanceId', 'token', 'sip_format',# 'sip_sessionid', 'v', 'fields','format'
login_keys = 'sip_apiname', 'sip_appkey', 'sip_sessionid', 'sip_redirecturl'

all_keys={
    'query_keys':['sip_appkey', 'sip_apiname', 'sip_sessionid', 'sip_service_command'],
    'unbind_keys':['sip_appkey', 'sip_apiname', 'sip_sessionid', 'sip_service_command'],
    'isLogin_keys':['sip_appkey', 'sip_apiname', 'sip_sessionid', 'sip_service_command','sip_tokentype' ],
    }

" all_dict "
all_dict= {
    'query_keys':{
        'sip_appkey':'16635',
        'sip_apiname':'taobao.shop.update',
        'sip_sessionid':response.session_id,
        'sip_service_command':'sip.user.query',
        },
    'unbind_keys':{
        'sip_appkey':'16635',
        'sip_apiname':'taobao.shop.update',
        'sip_sessionid':response.session_id,
        'sip_service_command':'sip.user.unbind',
        },
    'isLogin_keys':{    
        'sip_appkey':'16635',
        'sip_apiname':'taobao.shop.update',
        'sip_sessionid':response.session_id,
        'sip_service_command':'sip.user.isLogin',
        'sip_tokentype':'session',
        },
    }

" Class "
class MySip(object):
    """ Provides access to the Sip API. """

    iso_time_format = '%Y-%m-%d %X'
    sip_appkey = '16635'

    def __init__(self):
        pass

    def now_time(self):
        """ get now time. """
        stime = None
        if(time.timezone == 0):
            gmtimefix = 28800
            stime = time.gmtime(gmtimefix + time.time())
        else:
            stime = time.localtime()
        strtime = time.strftime(self.iso_time_format, stime)
        return strtime

    def db_config_select(self,name):
        my_taobao_config = db(db.config.name == name).select()
        my_taobao_config = my_taobao_config[0]
        return my_taobao_config

    def sip_dict_all(self,vars):
        """ Create my all dict. """
        sip_dict = {}
#        sip_dict['sip_apiname'] = 'alisoft.validateAppUser'
        sip_dict['sip_apiname'] = 'taobao.traderates.get'
#        sip_dict['sip_apiname'] = 'taobao.trades.bought.get'
#        sip_dict['sip_apiname'] = 'alisoft.validateUser'
        sip_dict['sip_timestamp'] = self.now_time()
        sip_dict['sip_appkey'] = self.sip_appkey
        sip_dict['sip_format'] = 'json'
        sip_dict['v'] = '1.0'
        sip_dict['sip_sessionid'] = response.session_id
#        sip_dict['nicks'] = 'tel800810'
        sip_dict['domainid'] = 3
        sip_dict['fields'] = 'title' #'id,nick,created,location.city'
        sip_dict.update(vars)
        try:
            sip_dict['userid'] = sip_dict['userId']
        except:
            pass
        return sip_dict

    def sip_sign(self,list,sip_dict):
        """ Create sign. """
        temp_dict = sip_dict
        cert_code = '5894b000a0bf11dd8d3cfee3c21c434f'
        keys_list = []
        for i in list:
            keys_list.append(i)
        keys_list.sort()
        sip_sign = ''
        for i in keys_list:
            sip_sign += i
            sip_sign += str(temp_dict[i])
        sip_sign = cert_code + sip_sign
        sip_sign = md5_hash(sip_sign)
        return sip_sign

    def sip_url(self,list,sip_dict):
        """ Create sip url only. """
        import copy
        url = ''
        try:
            temp_dict = copy.deepcopy(sip_dict)
            temp_dict['sip_timestamp'] = urllib.quote_plus(temp_dict['sip_timestamp'])
        except Exception:
            temp_dict = sip_dict
        for i in list:
            url += '%s=%s&' % (i, str(temp_dict[i]))
        return url

    def get_url(self, key, URL='http://sip.alisoft.com/sip/sipService',sip_sign=True):
        """ Get my url. """
        sip_dict = all_dict[key]
        keys_list = all_keys[key]
        sip_url = self.sip_url(keys_list, sip_dict)
        sip_url = URL + '?' + sip_url
        if sip_sign:
            sip_sign = self.sip_sign(keys_list, sip_dict)
            sip_url = sip_url + 'sip_sign=' + sip_sign
        return sip_url


#class Proxy(object):
#    """Represents a "namespace" of Facebook API calls."""
#
#    def __init__(self, client, name):
#        self._client = client
#        self._name = name
#
#    def __call__(self, method=None, args=None, add_session_args=True):
#        # for Django templates
#        if method is None:
#            return self
#
#        if add_session_args:
#            self._client._add_session_args(args)
#
#        return self._client('%s.%s' % (self._name, method), args)
#
#class AuthProxy(Namespace):
#    """Special proxy for sip.auth."""
#
#    def getSession(self):
#        """Sip API call. See ... """
#        args = {}        
#        args['auth_token'] = self._auth_token
##        try:
##            args['auth_token'] = self._auth_token
##        except AttributeError:
##            raise RuntimeError('Client does not have auth_token set.')
#        result = self._client('%s.getSession' % self._name, args)
#        self._client._session_key = result['session_key']
#        self._client._uid = result['uid']
#        self._client._secret = result.get('secret')
#        self._client._session_key_expires = result['expires']
#        return result
#
#    def createToken(self):
#        """Sip API call. See ... """
#        token = self._client('%s.createToken' % self._name)
#        self._client._auth_token = token
#        return token

   
#    # URL helpers
#    def get_url(self, page, **args):
#        """
#        Returns one of the Facebook URLs (www.facebook.com/SOMEPAGE.php).
#        Named arguments are passed as GET query string parameters.
#    
#        """
#        return 'http://www.facebook.com/%s.php?%s' % (page, urllib.urlencode(args))
#    
#    
#    def get_app_url(self, path=''):
#        """
#        Returns the URL for this app's canvas page, according to app_name.
#    
#        """
#        return 'http://apps.facebook.com/%s/%s' % (self.app_name, path)
#    
#    
#    def get_add_url(self, next=None):
#        """
#        Returns the URL that the user should be redirected to in order to add the application.
#    
#        """
#        args = {'api_key': self.api_key, 'v': '1.0'}
#    
#        if next is not None:
#            args['next'] = next
#    
#        return self.get_url('install', **args)
#    
#    
#    def get_authorize_url(self, next=None, next_cancel=None):
#        """
#        Returns the URL that the user should be redirected to in order to
#        authorize certain actions for application.
#    
#        """
#        args = {'api_key': self.api_key, 'v': '1.0'}
#    
#        if next is not None:
#            args['next'] = next
#    
#        if next_cancel is not None:
#            args['next_cancel'] = next_cancel
#    
#        return self.get_url('authorize', **args)
#    
#    
#    def get_login_url(self, next=None, popup=False, canvas=True):
#        """
#        Returns the URL that the user should be redirected to in order to login.
#    
#        next -- the URL that Facebook should redirect to after login
#    
#        """
#        args = {'api_key': self.api_key, 'v': '1.0'}
#    
#        if next is not None:
#            args['next'] = next
#    
#        if canvas is True:
#            args['canvas'] = 1
#    
#        if popup is True:
#            args['popup'] = 1
#    
#        if self._auth_token is not None:
#            args['auth_token'] = self._auth_token
#    
#        return self.get_url('login', **args)
#    
#    
#    def login(self, popup=False):
#        """Open a web browser telling the user to login to Facebook."""
#        import webbrowser
#        webbrowser.open(self.get_login_url(popup=popup))
#    
#    
#    def get_ext_perm_url(self, ext_perm, next=None, popup=False):
#        """
#        Returns the URL that the user should be redirected to in order to grant an extended permission.
#    
#        ext_perm -- the name of the extended permission to request
#        next     -- the URL that Facebook should redirect to after login
#    
#        """
#        args = {'ext_perm': ext_perm, 'api_key': self.api_key, 'v': '1.0'}
#    
#        if next is not None:
#            args['next'] = next
#    
#        if popup is True:
#            args['popup'] = 1
#    
#        return self.get_url('authorize', **args)
#    
#    
#    def request_extended_permission(self, ext_perm, popup=False):
#        """Open a web browser telling the user to grant an extended permission."""
#        import webbrowser
#        webbrowser.open(self.get_ext_perm_url(ext_perm, popup=popup))
    



#def getText(nodelist):
#    rc = ""
#    for node in nodelist.childNodes:
#        if node.nodeType == node.TEXT_NODE:
#            rc = rc + node.data
#    return rc
#
#def getTagText(root, tag):
#    node = root.getElementsByTagName(tag)[0]
#    rc = ""
#    for node in node.childNodes:
#        if node.nodeType in ( node.TEXT_NODE, node.CDATA_SECTION_NODE):
#            rc = rc + node.data
#    return rc

""" temp Class """
#my_sip = MySip()


if __name__ == '__main__':
    all_dict['isLogin_keys']
#    sip.login()
    print sip.__dict__
#    sip.taobao.items.get(fields=['iid', 'title', 'nick'], q='nike', sip_sessionid='sip_sessionid_temp')
#    sip.taobao.items.instock.get(fields=['iid', 'title', 'nick'], q='nike')

